package com.fujin.gulimall.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fujin.common.utils.R;
import com.fujin.gulimall.cart.Interceptor.CartInterceptor;
import com.fujin.gulimall.cart.feign.ProductFeign;
import com.fujin.gulimall.cart.service.CartService;
import com.fujin.gulimall.cart.vo.CartItemVo;
import com.fujin.gulimall.cart.vo.CartVo;
import com.fujin.gulimall.cart.vo.SkuInfoVo;
import com.fujin.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @title: CartServiceImpl
 * @Author uIn
 * @Date: 2022/3/16 22:19
 * @Version 1.0
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private ThreadPoolExecutor executor;


    //存入redis key的规则
    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItemVo addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //判断购物车是否有该购物项
        String productValue = (String) cartOps.get(skuId.toString());
        //如果没有就添加该购物项
        if (StringUtils.isEmpty(productValue)){
            //购物项信息
            CartItemVo cartItemVo = new CartItemVo();
            //使用异步
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程调用商品服务 根据skuId获取当前商品信息
                R info = productFeign.info(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                //2、设置购物项属性值
                cartItemVo.setCheck(true);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
                cartItemVo.setSkuId(skuId);
            }, executor);

            CompletableFuture<Void> AttrValues = CompletableFuture.runAsync(() -> {
                //远程调用商品服务，获取商品所有销售属性
                List<String> skuSaleAttrValues = productFeign.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);

            //需要等前面执行结束之后再执行后面的
            CompletableFuture.allOf(getSkuInfoTask,AttrValues).get();
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId,s);
            return cartItemVo;
        }else {
            //如果有就增加数量
            CartItemVo itemVo = JSON.parseObject(productValue, CartItemVo.class);
            itemVo.setCount(itemVo.getCount()+num);
            //修改redis的数据
            String cartItemJson = JSON.toJSONString(itemVo);
            cartOps.put(skuId.toString(),cartItemJson);
            return itemVo;
        }


    }

    /**
     * 重定向页面获取当前购物车中sku商品信息
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String redisValue = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);
        return cartItemVo;
    }

    /**
     * 获取购物车内容
     * 需要判断当前登录状态
     * 已登录需要合并【在线购物车】和【离线购物车】,并清空【离线购物车】
     * 未登录只需要获取【离线购物车】
     * @return
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            //已登录
            //1、获取在线购物车key
            String cartkey = CART_PREFIX+userInfoTo.getUserId();
            //2、获取临时购物车key
            String tempCartKey = CART_PREFIX+userInfoTo.getUserKey();
            //3、获取临时购物车内容
            List<CartItemVo> tempCart = getCartItem(tempCartKey);
            if (tempCart != null && tempCart.size() > 0){
                //临时购物车有数据需要进行合并操作
                for (CartItemVo cartItemVo : tempCart) {
                    //直接使用商品添加购物车方法
                    addCart(cartItemVo.getSkuId(),cartItemVo.getCount());
                }
                //清空临时购物车
                clearCart(tempCartKey);
            }
            //合并之后重新获取在线购物车内容就已经包含了临时购物车的数据了
            List<CartItemVo> cartItem = getCartItem(cartkey);
            cartVo.setItems(cartItem);
            return cartVo;
        }else {
            //未登录,直接获取临时购物车信息
            String tempCartKey = CART_PREFIX+userInfoTo.getUserKey();
            List<CartItemVo> cartItem = getCartItem(tempCartKey);
            cartVo.setItems(cartItem);
            return cartVo;
        }
    }

    /**
     * 获取key，得到只针对当前key操作的hash
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String key = "";
        if (userInfoTo.getUserId() != null){
            //说明用户登录了
            //将用户id作为key存入
            key = CART_PREFIX+userInfoTo.getUserId();
        }else {
            //没有登录
            //使用user-key作为key存入
            key = CART_PREFIX+userInfoTo.getUserKey();
        }
        //传入key，获取一个只针对当前key操作的hash
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);

        return hashOps;
    }

    /**
     * 封装根据用户key获取购物车数据
     * @param cartKey
     * @return
     */
    public List<CartItemVo> getCartItem(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            //将redis中的购物项value信息，封装CartItemVo进行返回
            List<CartItemVo> collect = values.stream().map(item -> {
                String s = (String) item;
                CartItemVo itemVo = JSON.parseObject(s, CartItemVo.class);
                return itemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }
}
